import matplotlib.pyplot as plt
import numpy as np
from sklearn.cluster import KMeans
from sklearn.datasets import load_iris

# 加载鸢尾花数据集
iris = load_iris()
X = iris.data[:, 2:4]  # 选择花瓣长度和花瓣宽度

# 绘制原始数据分布图
plt.scatter(X[:, 0], X[:, 1], c="red", marker='o', label='data points')
plt.xlabel('Petal length')
plt.ylabel('Petal width')
plt.legend(loc=2)
plt.title("Original Iris Data (Petal Length vs Petal Width)")
plt.show()

# 设置K值并进行K-means聚类
estimator = KMeans(n_clusters=3, random_state=42)  # K=3, 我们知道鸢尾花数据集有3个品种
estimator.fit(X)
label_pred = estimator.labels_  # 获取聚类标签

# 绘制K-means聚类结果
x0 = X[label_pred == 0]
x1 = X[label_pred == 1]
x2 = X[label_pred == 2]
plt.scatter(x0[:, 0], x0[:, 1], c="red", marker='o', label='Cluster 0')
plt.scatter(x1[:, 0], x1[:, 1], c="green", marker='*', label='Cluster 1')
plt.scatter(x2[:, 0], x2[:, 1], c="blue", marker='+', label='Cluster 2')

# 绘制质心
centers = estimator.cluster_centers_
plt.scatter(centers[:, 0], centers[:, 1], c='black', marker='x', s=200, label='Centroids')

plt.xlabel('Petal length')
plt.ylabel('Petal width')
plt.legend(loc=2)
plt.title("K-means Clustering (K=3)")
plt.show()

estimator = KMeans(n_clusters=2, random_state=42)  # K=2
estimator.fit(X)
label_pred_2 = estimator.labels_

# 绘制K=2的聚类结果
x0 = X[label_pred_2 == 0]
x1 = X[label_pred_2 == 1]
plt.scatter(x0[:, 0], x0[:, 1], c="red", marker='o', label='Cluster 0')
plt.scatter(x1[:, 0], x1[:, 1], c="blue", marker='+', label='Cluster 1')

centers = estimator.cluster_centers_
plt.scatter(centers[:, 0], centers[:, 1], c='black', marker='x', s=200, label='Centroids')

plt.xlabel('Petal length')
plt.ylabel('Petal width')
plt.legend(loc=2)
plt.title("K-means Clustering (K=2)")
plt.show()
